package com.naiterui.ehp.bs.esign.api.vo;

import com.naiterui.ehp.bp.support.exception.BusinessException;
import com.naiterui.ehp.bs.esign.exception.ExceptionCodes;
import lombok.Data;
import lombok.ToString;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;

/**
 * @author guoyongxiang
 * @date 2019/11/29 17:42
 * @since 1.0.0
 */
@Data
@ToString
public class SignFileSnVO implements Serializable {

    private static final Logger LOGGER = LoggerFactory.getLogger(SignFileSnVO.class);

    public final static String FILE_TYPE_RP = "RP";
    public final static String FILE_TYPE_EMR = "EMR";
    public final static String FILE_TYPE_GROUPCONSULT = "GS";
    public final static String FILE_TYPE_NS = "NS";

    public final static String USER_TYPE_DR = "0";
    public final static String USER_TYPE_PH = "1";
    public final static String USER_TYPE_AL_PH = "2";
    public final static String USER_TYPE_OTHER = "3";
    private static final long serialVersionUID = -1328653511253177379L;

    /**
     * 环境标识(D:开发, P:正式)
     */
    private String env;

    /**
     * 文件类型(RP:处方, EMR:病例, NS:免密)
     */
    private String fileType;

    /**
     * 用户类型(0:医生, 1:药师)
     */
    private String userType;

    /**
     * 用户ID
     */
    private Long userId;

    /**
     * 业务单号(处方编号、病例编号)
     */
    private String bizSn;

    public SignFileSnVO(String env, String fileType, String userType, Long userId, String bizSn) {
        this.env = env;
        this.fileType = fileType;
        this.userType = userType;
        this.userId = userId;
        this.bizSn = bizSn;
    }

    /**
     * {env}_{fileType}_{userType}_{userId}_{bizSn}
     * @param fileSn
     * @return
     */
    public static SignFileSnVO init(String fileSn){
        if(StringUtils.isNotBlank(fileSn)){
            String[] arr = fileSn.split("_");
            return new SignFileSnVO(arr[0], arr[1], arr[2], Long.valueOf(arr[3]), arr[4]);
        }
        return null;
    }

    public static String getFileSn(String env, String fileType, String userType, Long userId, String bizSn) throws BusinessException {
        if(StringUtils.isBlank(env) || StringUtils.isBlank(fileType) || StringUtils.isBlank(userType) || userId == null || StringUtils.isBlank(bizSn)){
            LOGGER.warn("参数不完整 env:{}, fileType:{}, userType:{}, userId:{}, bizSn:{}", env, fileType, userType, userId, bizSn);
            String paramStr = "env:%s, fileType:%s, userType:%s, userId:%d, bizSn:%s";
            String print = String.format(paramStr, env, fileType, userType, userId, bizSn);
            throw new BusinessException(ExceptionCodes.PARAM_ERROR, "待签文件编号生成参数不完整 " + print);
        }
        return env + "_" + fileType + "_" + userType + "_" + userId + "_" + bizSn;
    }
}
